package handler

import (
	"context"
	"fmt"
	"rpc/global"
	"rpc/models"
	__ "rpc/proto"
)

type Server struct {
	__.UnimplementedShopServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) List(_ context.Context, in *__.ListRequest) (*__.ListResponse, error) {
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var shop []models.Shops
	global.DB.Offset(int(offset)).Limit(int(pageSize)).Find(&shop)

	var shops []*__.List
	for _, v := range shop {
		list := &__.List{
			Name: v.Name,
			Ms:   v.Ms,
			Num:  int64(v.Num),
		}
		shops = append(shops, list)
	}
	return &__.ListResponse{
		List: shops,
	}, nil
}
func (s *Server) Info(_ context.Context, in *__.InfoRequest) (*__.InfoResponse, error) {
	var shop models.Shops
	global.DB.Where("id = ?", in.Id).Find(&shop)
	if shop.Id == 0 {
		return nil, fmt.Errorf("商品不存在 不允许展开")
	}
	return &__.InfoResponse{
		Name: shop.Name,
		Ms:   shop.Ms,
		Num:  int64(shop.Num),
	}, nil
}
func (s *Server) Login(_ context.Context, in *__.LoginRequest) (*__.LoginResponse, error) {
	var user models.Users
	global.DB.Where("tel = ?", in.Tel).Find(&user)
	if user.Id == 0 {
		return nil, fmt.Errorf("用户不存在 请先去注册")
	}
	if user.Password != in.Password || user.Tel != in.Tel {
		return nil, fmt.Errorf("账号或者密码不正确")
	}
	return &__.LoginResponse{
		Id: user.Id,
	}, nil
}
